package com.fs.service;

import com.fs.entity.Cleaner;
import com.fs.entity.Shop;
import com.fs.repository.CleanerRepository;
import com.fs.repository.ShopRepository;
import com.fs.service.bo.cleaner.BoCleaner;
import com.fs.service.bo.cleaner.BoCreateParam;
import com.fs.service.bo.cleaner.BoQueryParam;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.persistence.criteria.Predicate;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Validated
public class CleanerService {

    private final ShopRepository shopDao;
    private final CleanerRepository cleanerDao;

    public CleanerService(CleanerRepository cleanerDao, ShopRepository shopDao) {
        this.cleanerDao = cleanerDao;
        this.shopDao = shopDao;
    }

    public BoCleaner addCleaner(@Valid BoCreateParam param) {

        Optional<Shop> shop = shopDao.findById(param.getShopId());
        if (!shop.isPresent()) {
            throw new NotFoundException("请检查此店铺是否存在！");
        }

        Cleaner cleaner = new Cleaner();
        cleaner.setShop(shop.get());
        cleaner.setName(param.getName());
        cleaner.setPhone(param.getPhone());

        cleanerDao.save(cleaner);

        return new BoCleaner(cleaner);
    }

    public List<BoCleaner> getCleaners(@Valid BoQueryParam param) {
        Specification<Cleaner> spec = (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            String name = param.getName();
            String phone = param.getPhone();
            Integer shopId = param.getShopId();

            if (name != null) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + name + "%"));
            }
            if (phone != null) {
                predicates.add(criteriaBuilder.like(root.get("phone"), "%"+ phone + "%"));
            }
            if (shopId != null) {
                predicates.add(criteriaBuilder.equal(root.get("shop"), shopId));
            }
            int size = predicates.size();
            return criteriaQuery.where(predicates.toArray(new Predicate[size])).getRestriction();
        };

        return cleanerDao.findAll(spec).stream().map(BoCleaner::new).collect(Collectors.toList());
    }

    public void deleteCleanerById(int id) {
        if (!cleanerDao.existsById(id)) {
            throw new NotFoundException("此保洁员不存在！");
        }
        cleanerDao.deleteById(id);
    }
}
